#!/usr/bin/env python
#  -*- coding: utf-8 -*-
__author__ = 'chengzhi'

from tqsdk import TqApi, TqAuth
import datetime
# import csv
# import pandas as pd
api = TqApi(auth=TqAuth("houzx910", "houzx289310"))
# 获得 c2309 tick序列的引用
ticks = api.get_tick_serial("DCE.c2401")
# 获得 c2309 10秒K线的引用
# klines = api.get_kline_serial("DCE.c2309", 30)
# print("多合约K线：", klines)

# klines09 = api.get_kline_serial("DCE.c2309", 30)
# klines092 = api.get_kline_serial("DCE.c2309", 60)

klines01 = api.get_kline_serial("DCE.c2403", 30)
#klines03 = api.get_kline_serial("DCE.m2401", 30)
klines03 = api.get_kline_serial("SHFE.fu2403", 30)

klines05 = api.get_kline_serial("DCE.m2405", 30)
# klines11_day = api.get_kline_serial("DCE.c2311",  60*60*24)
# klines09_day = api.get_kline_serial("DCE.c2309",  60*60*24)



# klines09.to_csv('t09.csv')
# klines05.to_csv('t11.csv')
print("多合约K线：", klines01)
print("ticks",ticks)
print("ticks")
# print(datetime.datetime.fromtimestamp(klines.iloc[-1]["datetime"] / 1e9))

while True:
    api.wait_update()
    # 判断整个tick序列是否有变化
    # if api.is_changing(ticks):
        # ticks.iloc[-1]返回序列中最后一个tick
        # print("tick变化", ticks.iloc[-1])
    # 判断最后一根K线的时间是否有变化，如果发生变化则表示新产生了一根K线
    if api.is_changing(klines01.iloc[-1], "datetime"):
        # datetime: 自unix epoch(1970-01-01 00:00:00 GMT)以来的纳秒数
        print("01新线", datetime.datetime.fromtimestamp(klines01.iloc[-1]["datetime"] / 1e9))
    # 判断最后一根K线的收盘价是否有变化
    if api.is_changing(klines01.iloc[-1], "close"):
        # klines.close返回收盘价序列
        print("01变化", datetime.datetime.fromtimestamp(klines01.iloc[-1]["datetime"] / 1e9), klines01.close.iloc[-1])
    if api.is_changing(klines03.iloc[-1], "datetime"):
        print("                                         03新线", datetime.datetime.fromtimestamp(klines03.iloc[-1]["datetime"] / 1e9))
    if api.is_changing(klines03.iloc[-1], "close"):
        print("                                         03变化", datetime.datetime.fromtimestamp(klines03.iloc[-1]["datetime"] / 1e9), klines03.close.iloc[-1])
    if api.is_changing(klines05.iloc[-1], "datetime"):
        print("                                                                              05新线", datetime.datetime.fromtimestamp(klines05.iloc[-1]["datetime"] / 1e9))
    if api.is_changing(klines05.iloc[-1], "close"):
        print("                                                                              05变化", datetime.datetime.fromtimestamp(klines05.iloc[-1]["datetime"] / 1e9), klines05.close.iloc[-1])

